<template>
  <div class="feedback-container">
    <el-tabs v-model="activeTab" class="feedback-tabs">
      <el-tab-pane label="我的评价" name="my-feedback"></el-tab-pane>
      <el-tab-pane label="发表评价" name="add-feedback"></el-tab-pane>
    </el-tabs>

    <!-- 我的评价 -->
    <div v-if="activeTab === 'my-feedback'" class="feedback-list" v-loading="loading" element-loading-text="加载中...">
      <el-empty v-if="!loading && feedbackList.length === 0" description="暂无评价"></el-empty>
      <el-card v-for="feedback in feedbackList" :key="feedback.id" class="feedback-card">
        <div class="feedback-header">
          <div class="order-info">
            <span class="order-number">订单号：{{ feedback.orderNumber }}</span>
            <span class="feedback-time">评价时间：{{ formatDateTime(feedback.createTime) }}</span>
          </div>
          <div class="rating">
            <el-rate v-model="feedback.rating" disabled></el-rate>
          </div>
        </div>
        <div class="feedback-content">
          <div class="feedback-text">{{ feedback.content }}</div>
        </div>

      </el-card>

      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 发表评价 -->
    <div v-else class="add-feedback">
      <el-empty v-if="orderList.length === 0" description="暂无可评价的订单"></el-empty>
      <el-form v-else :model="feedbackForm" :rules="rules" ref="feedbackFormRef" label-width="100px">
        <el-form-item label="选择订单" prop="orderId">
          <el-select v-model="feedbackForm.orderId" placeholder="请选择要评价的订单" style="width: 100%">
            <el-option
              v-for="order in orderList"
              :key="order.id"
              :label="getOrderLabel(order)"
              :value="order.id"
            >
              <div class="order-option">
                <div class="order-number">订单号：{{ order.number }}</div>
                <div class="order-time">下单时间：{{ formatDateTime(order.orderTime) }}</div>
                <div class="order-dishes" v-if="order.orderDetails && order.orderDetails.length > 0">
                  <div class="dishes-title">餐品内容：</div>
                  <div class="dishes-list">
                    <span class="dish-item" v-for="(detail, index) in order.orderDetails" :key="index">
                      {{ detail.dishName }}({{ detail.number }}份)
                      <span v-if="index < order.orderDetails.length - 1">、</span>
                    </span>
                  </div>
                </div>
                <div class="order-amount">总金额：¥{{ parseFloat(order.amount).toFixed(2) }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="feedbackForm.rating" :colors="colors"></el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitFeedback" :loading="submitLoading">提交评价</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { feedbackApi, orderApi } from '../../api/index'
import { useRoute } from 'vue-router'

const route = useRoute()
const activeTab = ref('my-feedback')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 评价列表
const feedbackList = ref<any[]>([])

// 可评价的订单列表
const orderList = ref<any[]>([])

// 评价表单
const feedbackFormRef = ref<FormInstance>()
const submitLoading = ref(false)
const feedbackForm = reactive({
  orderId: 0,
  rating: 5,
  content: ''
})

// 加载评价列表
const loadFeedbacks = async () => {
  loading.value = true
  try {
    const res = await feedbackApi.getUserFeedbacks(currentPage.value, pageSize.value)
    feedbackList.value = res.data.records || []
    total.value = res.data.total || 0

    // 处理订单号
    for (const feedback of feedbackList.value) {
      if (feedback.orderId) {
        try {
          const orderRes = await orderApi.getOrderDetail(feedback.orderId)
          feedback.orderNumber = orderRes.data.number
        } catch (error) {
          console.error(`获取订单${feedback.orderId}详情失败:`, error)
          feedback.orderNumber = `订单ID: ${feedback.orderId}`
        }
      } else {
        feedback.orderNumber = '未关联订单'
      }
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取评价列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间为更友好的格式
const formatDateTime = (dateTimeStr: string | null | undefined): string => {
  if (!dateTimeStr) return '暂无数据'

  try {
    const date = new Date(dateTimeStr)

    // 获取当前日期
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const yesterday = new Date(today)
    yesterday.setDate(yesterday.getDate() - 1)

    // 检查是否是今天
    if (date >= today) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 检查是否是昨天
    if (date >= yesterday && date < today) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 如果是今年的其他日期
    const currentYear = now.getFullYear()
    if (date.getFullYear() === currentYear) {
      return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    }

    // 如果是其他年份
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateTimeStr // 如果解析失败，返回原始字符串
  }
}

// 加载可评价的订单列表
const loadOrders = async () => {
  try {
    const res = await orderApi.getUserOrders(1, 100)
    // 筛选出已完成的订单
    const completedOrders = (res.data.records || []).filter((order: {status: number}) => order.status === 4)

    // 获取每个订单的详情信息
    for (const order of completedOrders) {
      try {
        const detailRes = await orderApi.getOrderDetail(order.id)
        if (detailRes.data) {
          // 将订单详情添加到订单对象中
          order.orderDetails = detailRes.data.orderDetails || []
        }
      } catch (error) {
        console.error(`获取订单${order.id}详情失败:`, error)
        order.orderDetails = []
      }
    }

    orderList.value = completedOrders
  } catch (error: any) {
    ElMessage.error(error.message || '获取订单列表失败')
  }
}

// 表单验证规则
const rules = {
  orderId: [
    { required: true, message: '请选择要评价的订单', trigger: 'change' }
  ],
  rating: [
    { required: true, message: '请给出评分', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 评分颜色
const colors = ['#F56C6C', '#F56C6C', '#E6A23C', '#E6A23C', '#67C23A']

// 生成订单标签，包含订单号和菜品信息
const getOrderLabel = (order: any): string => {
  if (!order) return '未知订单'

  let label = `${order.number}`

  // 添加菜品信息
  if (order.orderDetails && order.orderDetails.length > 0) {
    const dishNames = order.orderDetails.map((detail: any) => detail.dishName)
    // 最多显示3个菜品名称，避免标签过长
    const displayDishes = dishNames.slice(0, 3)
    if (dishNames.length > 3) {
      displayDishes.push('等')
    }
    label += ` - ${displayDishes.join('、')}`
  }

  return label
}

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadFeedbacks()
}

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadFeedbacks()
}

// 提交评价
const submitFeedback = async () => {
  if (!feedbackFormRef.value) return

  await feedbackFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 调用API提交评价
        await feedbackApi.submitFeedback({
          orderId: feedbackForm.orderId,
          rating: feedbackForm.rating,
          content: feedbackForm.content
        })

        ElMessage.success('评价提交成功')
        activeTab.value = 'my-feedback'

        // 重新加载评价列表
        await loadFeedbacks()

        // 重置表单
        resetForm()
      } catch (error: any) {
        console.error('评价提交失败:', error)
        ElMessage.error(error.message || '评价提交失败，请稍后再试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (feedbackFormRef.value) {
    feedbackFormRef.value.resetFields()
  }
  feedbackForm.orderId = 0
  feedbackForm.rating = 5
  feedbackForm.content = ''
}

// 组件挂载时加载数据
onMounted(async () => {
  // 如果URL中有orderId参数，切换到发表评价标签页
  const orderId = route.query.orderId
  if (orderId) {
    activeTab.value = 'add-feedback'
    feedbackForm.orderId = Number(orderId)
  }

  // 加载评价列表
  await loadFeedbacks()

  // 加载可评价的订单列表
  await loadOrders()
})
</script>

<style scoped>
.feedback-container {
  padding: 20px;
}

.feedback-tabs {
  margin-bottom: 20px;
}

.feedback-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.order-number {
  font-weight: bold;
  margin-right: 20px;
}

.feedback-time {
  color: #409EFF;
  font-weight: 500;
  margin-left: 15px;
}

.feedback-content {
  margin-bottom: 15px;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.feedback-text {
  line-height: 1.6;
  color: #333;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-option {
  display: flex;
  flex-direction: column;
  padding: 10px 0;
  width: 100%;
}

.order-number {
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.order-time {
  color: #409EFF;
  font-size: 13px;
  margin-bottom: 8px;
}

.order-dishes {
  color: #666;
  font-size: 13px;
  margin-bottom: 8px;
  line-height: 1.4;
  white-space: normal;
  word-break: break-all;
}

.dishes-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.dishes-list {
  padding-left: 8px;
}

.dish-item {
  display: inline-block;
}

.order-amount {
  color: #F56C6C;
  font-weight: bold;
  font-size: 14px;
  margin-top: 5px;
}
</style>
